#!/usr/local/bin/python3
# -*- coding: UTF-8 -*-
import re
import os
import shutil
import sys
from Script.splitScriptFile import *
from Script.readConfig import *
from Common import *
currentpath = os.getcwd()
  # @私有
    # #拆分变量内容得到应该替换为self.param的变量

def splitParamContent( param):

        pos1 = param.find("=")
        pos2 = param.find(",")
        if pos1 != -1:
            return str(param[:pos1])
def prePareParam(paramContent):
        f = open(currentpath+"/Sticker/Sticker/"+"TS.lua", "w+")  # your path!
        f.write(paramContent)
        f.close()
        paramContent = ""
        selfparam = []
        validSelfParam = []
        f = open(currentpath+"/Sticker/Sticker/"+"TS.lua", "r")  # your path!
        for line in f.readlines():
            if line == '\n':
                line = line.strip("\n")
            selfparam.append(splitParamContent(line))
            paramContent = paramContent+line
        f.close()
        for i in selfparam:
            if i != None:
                i = i.strip()
            if (not(i is None) and str(i) != "makeup"and str(i) != "eyeLinerPath" and str(i) != "oldEyeShadowLayer1BlendMode" and str(i) != "oldEyeShadowLayer2BlendMode"):
                validSelfParam.append(i)
        paramContent = paramContent.replace("\n", ",\n")
            
        return validSelfParam

def analysisScript(path, fileName, zipByJsonContent):

    requireStart = 0
    requireEnd = 0

    paramStart = 0
    paramEnd = 0

    requireStart, requireEnd = getRequireContent(path)

    functionCount = getFunctionCount(path)
    if functionCount >= 2:
        functionContent = [0 for i in range(1, functionCount+1)]

        paramStart = requireEnd
        paramEnd = getParamContent(path, 1)

        initStart = paramEnd+1
        initEnd = getParamContent(path, 2)
        initEnd = initEnd - (getEndSymbolLine(path, str(loadDataSet(path, 1, initEnd)), initStart))

        if functionCount >2:
            frameStart = getParamContent(path, 2)+1
            frameEnd = getParamContent(path, 3)

            frameEnd = frameEnd - (getEndSymbolLine(path, str(loadDataSet(path, frameStart, frameEnd)), frameStart))
        else:
            frameStart = getParamContent(path, 2)+1
            frameEnd = getEndLine(path)-1    
        
        requireContent = loadDataSet(path, requireStart, requireEnd)

        requireList = requireContent.replace("require", "")
        requireList = requireList.replace(".lua\"", ".lua\",")
        configString = splitStringByIndex(path, splitString(path, "/"), 0)

        configString = getConfig(configString, requireList)

        paramContent = loadDataSet(path, paramStart, paramEnd)
        
        functionContent[0] = loadDataSet(path, initStart, initEnd)
        functionContent[1] = loadDataSet(path, frameStart, frameEnd)
        for i in range(functionCount):

            if i >= 2:
                i = i+1
                start = getParamContent(path, i)+1
                end = getParamContent(path, i+1)
                end = end - (getEndSymbolLine(path, str(loadDataSet(path, start, end)), start))
                if i == functionCount:
                    end = getEndLine(path)-1

                functionContent[i-1] = loadDataSet(path, start-1, end+1)
        # ---准备替换方法名为self.
        selfFunctionContent = [0 for i in range(1, functionCount+1)]
        selfFunctionContent[0]="initialize"
        selfFunctionContent[1]="frameReady"     
        for i in range(len(functionContent)):
            if i >= 2:
                selfFunctionContent[i]=(str(functionContent[i][functionContent[i].find("function")+len("function"): functionContent[i].find("(")]).strip())   
        paramContent=prePareParam(paramContent)
        paramContent.append("makeup")
        paramContent.append("scene")
       
        for i in range(len(functionContent)):
            lines = []
            f = open(currentpath+"/Sticker/Sticker/"+"TS.lua", "w+")  # your path!
            # for item in functionContent:
            f.write((functionContent[i]))
            f.close()
            functionContent[i]=""
            f = open(currentpath+"/Sticker/Sticker/"+"TS.lua", "r")
            for line in f:
                for item in selfFunctionContent:
                    
                    if line.find("function")!=-1:
                        break    
                    else:
                        pos = line.find(item)
                        
                        if pos!=-1:

                            str1 = ( line[pos-1:pos])
                            str2 = ( line[pos+len(item):pos+len(item)+1])
                           
                            pattern = re.compile('[A-Za-z0-9]+')
                            match1 = pattern.findall(str1)
                            match2 = pattern.findall(str2)
                            
                            if match1 or match2:
                                # print ('not contains digital')
                                pass
                            else:
                                # 替换内容中的方法名称为self.  剔除包含此方法名的字符串
                                line=line.replace(item,"self."+item)
                
                for item in paramContent:
                    if line.find("function")!=-1:
                        break    
                    else: 
                        pos = line.find(item)
                        
                        if pos!=-1:

                            str1 = ( line[pos-1:pos])
                            str2 = ( line[pos+len(item):pos+len(item)+1])
                            # print(str1)
                            # print(str2)
                            pattern = re.compile('[A-Za-z0-9]+')
                            match1 = pattern.findall(str1)
                            match2 = pattern.findall(str2)
                            # print(match1)
                            # print(match2)
                            if match1 or match2:
                                # print ('not contains digital')
                                pass
                            else:
                                # 替换内容中的方法名称为self.  剔除包含此方法名的字符串
                                line=line.replace(item,"self."+item)
        
                # lines.append(line)
                line=line.replace("img/",fileName+"/img/")    
                line=line.replace("self.makeup_param/","makeup_param")  
                functionContent[i]=functionContent[i]+line

            f.close()
          
        
        # # ------------以上准备好内容--------------

        lines = []
        f = open(currentpath+"/Sticker/Sticker/"+"TS.lua", "w+")  # your path!
        f.write(zipByJsonContent)
        f.close()
        f = open(currentpath+"/Sticker/Sticker/"+"TS.lua", "r")
        for line in f:
            lines.append(line)
            if line.find("function")!=-1:
                if line.find(":Initialize") != -1:
                    lines.append(functionContent[0])
                elif line.find(":FrameReady") != -1:
                    lines.append(functionContent[1])
        f.close()

        s = ''.join([str(x) for x in lines])
        

        f = open(currentpath+"/Sticker/Sticker/"+"TS.lua", "w+")
        f.write(configString)
        f.write(s)
        for i in range(len(functionContent)):
            if i >= 2:
                f.write(str(functionContent[i]).replace("function ", "function "+str(fileName)+":"))

        f.close()
        f = open(currentpath+"/Sticker/Sticker/"+"TS.lua", "r")
        zipByJsonContent = f.read()
        f.close()
        os.remove(currentpath+"/Sticker/Sticker/"+"TS.lua")
   
    return zipByJsonContent,paramContent,selfFunctionContent

